package com.apache.gmall.util;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSONObject;
import com.apache.gmall.common.GmallConfig;
import org.apache.commons.lang.StringUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Set;

public class PhoenixUtil {

    //TODO 工具类的异常抛出去就行，写这个工具类是为了更多人直接调用，每个人遇到的异常不一样，业务不同，处理异常的方式也不一样

    //phoenix的新增和修改都是upsert

    /**
     * @param connection phoenix 连接
     * @param sinkTable  表名  tn
     * @param data       数据  {"id":"1001","name":"zhangsan","sex":"male"}
     */
    public static void upsertValue(DruidPooledConnection connection, String sinkTable, JSONObject data) throws SQLException {

        //1.拼接SQL语句：upsert into db.tn(id,name,sex) values('1001','zhangsan','male')
        Set<String> columns = data.keySet();
        Collection<Object> values = data.values();
        String sql = "upsert into " + GmallConfig.HBASE_SCHEMA + "." + sinkTable + "(" +
                StringUtils.join(columns, ",") + ") values ('" +
                StringUtils.join(values, "','") + "')";



        //2.预编译SQL:
        PreparedStatement preparedStatement = connection.prepareStatement(sql);

        //3.执行:
        preparedStatement.execute();
        connection.commit();

        //4.释放资源
        connection.close();

    }
}
